require File.expand_path(File.dirname(__FILE__) + '/parser')
require 'yaml'

module ParamsDebugger
  class Debugger
    def initialize output, args
      @output = output
      @args = args
    end
  
    def start
      actions.each do |action|
        if plain_version? options
          @output.puts parameters action
        else
          @output.puts humanize(parameters action)
        end
      end
    end
    
    private
    
    def humanize parameters
      if parameters.match /^\{.*\}$/
        eval "#{parameters}.to_yaml"
      else
        parameters
      end
    end
    
    def parameters action
      result = cat action
      
      result.gsub!(/^\s*Parameters:\s*/, '')
      
      result.strip
    end
    
    def cat action
      `cat #{log} | grep #{action} -A 1 | grep Parameters | tail -1`
    end
    
    def actions
      @actions ||= ParamsDebugger::Parser::parse_actions @args
    end
    
    def options
      @options ||= ParamsDebugger::Parser::parse_options @args
    end
    
    def log
      @log ||= ParamsDebugger::Parser::parse_log options
    end
    
    def plain_version? options
      options.include?('plain') || options.include?('p')
    end
  end
end
